/**
 * connect自身的中间件
 */
var http = require('http');
var connect = require('connect');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var limit = require('./limit');
var logger = require('morgan');
var fs = require('fs');
var path = require('path');
var favicon = require('serve-favicon');
var auth = require('basic-auth')
var serveStatic = require('serve-static');//静态文件服务
var compression = require('compression');//gzip压缩
var directory = require('serve-index');//提供目录
var log = fs.createWriteStream(path.join(__dirname, 'temp.log'), {
    flags: 'a'
});
var KEY = 'just once '; //cookie签名秘钥
var app = connect()
	.use(compression())
	.use(favicon(path.join(__dirname, 'favicon.ico')))
    // .use(limit({"limit":"2mb"}))
    .use(directory(__dirname))
    .use(serveStatic(__dirname))
    .use(logger('dev')).use(logger("dev", {
        stream: log
    })).use(cookieParser(KEY)).use(bodyParser.json()).use(bodyParser.urlencoded({
        extended: false
    })).use('/admin', function(req, res, next) {
        var user = auth(req);
        console.log(user);
        if (user && user.name && user.name === 'admin' && user.pass && user.pass === '123') {
            next();
        } else {
            res.statusCode = 401;
            res.setHeader('WWW-Authenticate', 'Basic ');
            res.end('Unauthorized');
        }
    }).use('/admin', function(req, res) {
        res.end('welcome I am secret');
    }).use(function(req, res) {
        console.log(req.method + " " + req.url);
        console.log(req.cookies);
        console.log(req.signedCookies);
        console.log(req.body.username);
        console.log('---------------');
        res.setHeader('Set-Cookie', 'name=quyman'); //被无视掉
        res.setHeader('Set-Cookie', 'SESSIONID=aef121aes;Expires=Tue, 08 Jun 2021 10:10:13 GMT');
        res.end('fuck');
    });
http.createServer(app).listen(3409, function(err) {
    if (!err) {
        console.log('server start on port 3409');
    }
});